using MediatR;
using Microsoft.AspNetCore.Mvc;
using TerritoryGame.Application.Queries;

namespace TerritoryGame.API.Controllers;

[ApiController]
[Route("api/queries")]
public class QueryController : ControllerBase
{
    private readonly IMediator _mediator;
    
    public QueryController(IMediator mediator)
    {
        _mediator = mediator;
    }
    
    [HttpGet("rooms")]
    public async Task<ActionResult<GetRoomsResult>> GetRooms()
    {
        var query = new GetRoomsQuery();
        var result = await _mediator.Send(query);
        if (!result.Success)
        {
            return BadRequest(result);
        }
        return Ok(result);
    }
    
    [HttpGet("rooms/{roomId}")]
    public async Task<ActionResult<GetRoomResult>> GetRoom(string roomId)
    {
        // 尝试解析为GUID，如果失败则作为房间代码处理
        if (Guid.TryParse(roomId, out var guid))
        {
            var query = new GetRoomQuery { RoomId = guid };
            var result = await _mediator.Send(query);
            if (!result.Success)
            {
                return NotFound(result);
            }
            return Ok(result);
        }
        else
        {
            // 作为房间代码处理
            var query = new GetRoomByCodeQuery { RoomCode = roomId };
            var result = await _mediator.Send(query);
            if (!result.Success)
            {
                return NotFound(result);
            }
            return Ok(result);
        }
    }
    
    [HttpGet("games/{gameId}/state")]
    public async Task<ActionResult<GetGameStateResult>> GetGameState(Guid gameId)
    {
        var query = new GetGameStateQuery { GameId = gameId };
        var result = await _mediator.Send(query);
        if (!result.Success)
        {
            return NotFound(result);
        }
        return Ok(result);
    }
    
    [HttpGet("games/{gameId}/stats")]
    public async Task<ActionResult<GetGameStatsResult>> GetGameStats(Guid gameId)
    {
        var query = new GetGameStatsQuery { GameId = gameId };
        var result = await _mediator.Send(query);
        if (!result.Success)
        {
            return NotFound(result);
        }
        return Ok(result);
    }
}
